<template>
  <div class="variable-stability">
    <a-form layout="inline" class="inline-form" :form="form">
      <a-card title="模型选择" :bordered="false">
        <a-form-item label="模型选择" class="form-item">
          <a-select
            placeholder="请选择模型"
            style="width: 320px"
            v-decorator="[
              'modelUuid',
              {
                rules: [{ required: true, message: '请选择模型' }],
              },
            ]"
            @change="handleChange"
          >
            <a-select-option v-for="item in modelList" :key="item.uuid" :value="item.uuid">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="模型版本" class="form-item">
          <a-select
            placeholder="请选择版本"
            style="width: 320px"
            v-decorator="[
              'version',
              {
                rules: [{ required: true, message: '请选择版本' }],
              },
            ]"
          >
            <a-select-option v-for="item in versionList" :key="item" :value="item">
              {{ item }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-card>
      <a-card title="分箱设置" :bordered="false">
        <a-form-item label="分箱方式" class="form-item">
          <a-select placeholder="请选择分箱方式" style="width: 200px" v-model="binType">
            <a-select-option value="0">自定义</a-select-option>
            <a-select-option value="1">0-1分十等分</a-select-option>
            <a-select-option value="2">0-100分十等分</a-select-option>
            <a-select-option value="3">300-900分十等分</a-select-option>
          </a-select>
          <a-tooltip
            title="系统会尝试读取建模时分箱规则，若没有获取到规则，则需要下载模版，填充分箱规则后上传，要求CSV格式"
          >
            <a-icon type="question-circle" theme="filled" class="question-icon" />
          </a-tooltip>
          <a-space v-if="binType === '0'" class="upload-space">
            <a-tooltip title="文件大小在100M以内，此操作将覆盖已有分箱配置！">
              <a-upload
                name="file"
                :multiple="false"
                :fileList="[]"
                @change="handleFileChange"
                :before-upload="beforeUpload"
              >
                <a-button> <a-icon type="upload" /> 上传分箱规则 </a-button>
              </a-upload>
            </a-tooltip>
            <a href="http://47.100.43.220:8088/modelApi/downloadMonitorTemp" target="_blank" download>模版下载</a>
          </a-space>
        </a-form-item>
        <a-form-item label="变量" class="form-item" v-if="binType !== '0'">
          <a-select v-model="selectedVariable" style="width: 200px" placeholder="请选择模型出入参变量" mode="multiple">
            <a-select-option v-for="item in variableList" :key="item" :value="item">
              {{ item }}
            </a-select-option>
          </a-select>
          <a-button type="link" @click="handleSetRule">设置规则</a-button>
        </a-form-item>
        <a-collapse v-if="ruleList.length" accordion v-model="activeKey">
          <a-collapse-panel v-for="(item, index) in ruleList" :key="`${index}`">
            <template slot="header">
              <a-space>
                <a-tag color="blue" v-for="name in item.name" :key="name">
                  {{ name }}
                </a-tag>
              </a-space>
            </template>
            <template slot="extra">
              <a-button type="link" @click.stop="handleEditClick(item)">编辑</a-button>
              <a-button type="link" @click.stop="handleDeleteClick(item)">删除</a-button>
            </template>
            <RuleTableList
              :data="item.data"
              :is-editing="item.isEditing"
              @data-changed="(data) => handleDataChanged(item, data)"
              @cancel-edit="handleCancelEdit(item)"
            />
          </a-collapse-panel>
        </a-collapse>
      </a-card>
      <a-card title="统计基准" :bordered="false">
        <a-form-item label="统计基准对比" class="form-item">
          <a-space>
            <a-checkbox v-decorator="['compareB', { valuePropName: 'checked', initialValue: true }]">
              跟建模对比
            </a-checkbox>
            <a-checkbox v-decorator="['compareD', { valuePropName: 'checked' }]" @change="handleCompareDChange">
              跟昨天对比
            </a-checkbox>
            <a-switch
              v-if="compareD"
              v-decorator="['compareDw', { valuePropName: 'checked' }]"
              checked-children="包含周末"
              un-checked-children="不含周末"
            />
            <a-tooltip title="关闭状态统计的昨天将跳过周末" v-if="compareD">
              <a-icon type="question-circle" theme="filled" />
            </a-tooltip>
            <a-checkbox v-decorator="['compareW', { valuePropName: 'checked' }]"> 跟上周对比 </a-checkbox>
            <a-checkbox v-decorator="['compareM', { valuePropName: 'checked' }]"> 跟上月对比 </a-checkbox>
          </a-space>
        </a-form-item>
      </a-card>
      <a-card title="开关控制" :bordered="false">
        <a-form-item label="监控生效开关" class="form-item">
          <a-switch
            v-decorator="['status', { valuePropName: 'checked' }]"
            checked-children="开"
            un-checked-children="关"
          />
        </a-form-item>
      </a-card>
    </a-form>
    <a-divider />
    <div style="text-align: center">
      <a-space>
        <a-button @click="handleCancel">取消</a-button>
        <a-button type="primary" @click="handleSubmit" :disabled="disabled">提交</a-button>
      </a-space>
    </div>
  </div>
</template>

<script>
import { getAllModel } from '@/api/monitor'
import { getMonitorConfig, getModelFields, uploadMonitorTemplate, setMonitorConfig } from '@/api/manage'
import RuleTableList from './RuleTableList'
import { ruleInitMap } from './config'

export default {
  name: 'VariableStability',
  components: {
    RuleTableList,
  },
  props: {
    modelDetail: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    const modelData = this.modelDetail
    return {
      form: this.$form.createForm(this),
      activeKey: '',
      modelData,
      modelList: [],
      versionList: [],
      dataSource: [],
      ruleDetail: null,
      ruleList: [],
      selectedVariable: [],
      binType: '0',
      compareD: false, // 添加 compareD 状态跟踪
    }
  },
  computed: {
    variableList() {
      // 从dataSource数组中过滤ruleList的name数组中已存在的变量
      const variableName = this.ruleList.flatMap((item) => item.name)
      return this.dataSource.filter((item) => !variableName.includes(item))
    },
    // 判断表单有空值时无法提交
    disabled() {
      return this.ruleList.length === 0
    },
  },
  mounted() {
    this.getModelList()
    this.getInitData()
  },
  methods: {
    async getModelList() {
      try {
        const res = await getAllModel()
        if (res.code === 200) {
          this.modelList = res.data
          this.$nextTick(() => {
            this.form.setFieldsValue({
              modelUuid: this.modelData.uuid,
              version: this.modelData.version,
            })
          })
        }
      } catch (error) {
        console.log(error)
      }
    },
    handleChange(val) {
      const _this = this
      this.$confirm({
        title: '警告',
        content: '更改"模型名称"将丢失当前模型性能配置，确认更改吗？',
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          _this.versionList = [_this.modelList.find((item) => item.uuid === val).version]
          _this.modelData.version = _this.versionList[0]
          _this.modelData.uuid = val
          _this.getInitData()
        },
        onCancel() {
          console.log('Cancel')
        },
      })
    },
    getInitData() {
      getMonitorConfig({
        modelUuid: this.modelData.uuid,
        version: this.modelData.version,
      }).then((res) => {
        if (res.code === 200 && res.data) {
          this.ruleDetail = res.data
          const rule = JSON.parse(res.data.binRuleDetails)
          const buildRule = JSON.parse(res.data.buildProportion)
          this.ruleList = Object.keys(rule).map((key) => {
            return {
              name: [key],
              data: Object.keys(rule[key]).map((k) => {
                return {
                  key: k,
                  binRuleDetails: rule[key][k],
                  buildProportion: buildRule[key][k],
                }
              }),
            }
          })
          // 先设置 compareD 的值，确保条件渲染正确
          this.compareD = this.ruleDetail.compareD
          // 使用 $nextTick 确保 DOM 更新后再设置表单值
          this.$nextTick(() => {
            this.form.setFieldsValue({
              compareB: this.ruleDetail.compareB,
              compareD: this.ruleDetail.compareD,
              compareDw: this.ruleDetail.compareDw,
              compareW: this.ruleDetail.compareW,
              compareM: this.ruleDetail.compareM,
              status: !!this.ruleDetail.status,
            })
          })
        } else {
          // 清空数据
          this.form.resetFields()
          this.ruleList = []
          // 设置初始值
          this.form.setFieldsValue({
            modelUuid: this.modelData.uuid,
            version: this.modelData.version,
            compareB: true,
            compareD: false,
            compareDw: false,
            compareW: false,
            compareM: false,
            status: false,
          })
        }
      })
      getModelFields({
        modelUuid: this.modelData.uuid,
        version: this.modelData.version,
      }).then((res) => {
        if (res.code === 200) {
          this.dataSource = res.data
        }
      })
    },
    handleEditClick(item) {
      this.$set(item, 'isEditing', true)
    },
    handleDeleteClick(item) {
      this.ruleList = this.ruleList.filter((i) => i !== item)
    },
    handleCancelEdit(item) {
      this.$set(item, 'isEditing', false)
    },
    handleDataChanged(item, data) {
      this.$set(item, 'data', data)
      this.$set(item, 'isEditing', false)
    },
    handleSetRule() {
      const { selectedVariable } = this
      if (selectedVariable.length === 0) {
        this.$message.error('请选择变量')
        return
      }
      // 判断数据是否存在若存在则更新,不存在则新增
      const index = this.ruleList.findIndex((item) => item.name.includes(selectedVariable[0]))
      if (index !== -1) {
        this.ruleList[index].data = ruleInitMap[this.binType]
        this.$set(this.ruleList[index], 'isEditing', true)
        this.$set(this.ruleList[index], 'name', selectedVariable)
        // 设置激活面板
        this.activeKey = `${index}`
      } else {
        this.ruleList.push({
          name: selectedVariable,
          data: ruleInitMap[this.binType],
          isEditing: true,
        })
        // 新增规则时，设置 activeKey 为新增的索引
        this.activeKey = `${this.ruleList.length - 1}`
      }
    },
    // 文件上传前验证
    beforeUpload(file) {
      // 根据文件类型进行不同的验证
      const isCSV = file.name.toLowerCase().endsWith('.csv')
      if (!isCSV) {
        this.$message.error('模板文件只支持 .csv 格式的文件')
        return false
      }

      const isLt100M = file.size / 1024 / 1024 < 100
      if (!isLt100M) {
        this.$message.error('文件大小不能超过100MB')
        return false
      }

      // 返回 false 阻止自动上传
      return false
    },
    handleFileChange(info) {
      const { file } = info
      const formData = new FormData()
      formData.append('monitorFile', file)
      formData.append('version', this.modelData.version)
      formData.append('modelUuid', this.modelData.uuid)
      uploadMonitorTemplate(formData).then((res) => {
        if (res.code === 200) {
          this.$message.success(res.message)
          this.ruleList = Object.keys(res.data).map((key) => {
            return {
              name: [key],
              data: res.data[key].map((item) => {
                return {
                  key: item.label,
                  binRuleDetails: item.range,
                  buildProportion: item.trainPercent,
                }
              }),
            }
          })
        }
      })
    },
    handleCompareDChange(e) {
      this.compareD = e.target.checked
    },
    handleSubmit() {
      this.form.validateFields((errors, values) => {
        if (errors) {
          return
        }
        const { status } = values
        const binRuleDetails = {}
        const buildProportion = {}
        this.ruleList.forEach((item) => {
          item.name.forEach((name) => {
            const rule1 = {}
            const rule2 = {}
            item.data.forEach((data) => {
              rule1[data.key] = data.binRuleDetails
              rule2[data.key] = data.buildProportion
            })
            binRuleDetails[name] = rule1
            buildProportion[name] = rule2
          })
        })
        const formData = {
          ...values,
          status: Number(status),
          binRulesDetails: JSON.stringify(binRuleDetails),
          buildProportion: JSON.stringify(buildProportion),
        }
        setMonitorConfig(formData).then((res) => {
          if (res.code === 200) {
            this.$message.success(res.message)
            this.handleCancel()
            this.$emit('refresh')
          }
        })
      })
    },
    handleCancel() {
      this.$emit('close')
    },
  },
}
</script>

<style lang="less" scoped>
.variable-stability {
  .inline-form {
    .form-item {
      .question-icon {
        margin-left: 8px;
        font-size: 12px;
        margin-right: 12px;
      }
    }
  }
}

.upload-space {
  align-items: flex-start;
}
</style>
